<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
        type="danger"
        round
        plain
        size="mini"
        class="edit-btn"
        @click="isEdit = !isEdit"
        >{{ isEdit ? "完成" : "编辑" }}</van-button
      >
    </van-cell>

    <van-grid class="my-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        :text="channel.name"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          slot="icon"
          name="clear"
          v-show="isEdit && !fiexChannels.includes(channel.id)"
        ></van-icon>
        <span class="text" slot="text" :class="{ active: index === active }">{{
          channel.name
        }}</span>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title">频道推荐</div>
    </van-cell>

    <van-grid class="recommend-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in recommendChannels"
        :key="index"
        :text="channel.name"
        icon="plus"
        @click="onAddChannel(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import {
  getAllChannels,
  addUserChannels,
  deleteUserChannel,
} from "@/api/channel";
import { mapState } from "vuex";
import { setItem } from "@/utils/storage";

export default {
  name: "ChannelEdit",
  props: {
    myChannels: {
      type: Array,
      requires: true,
    },
    active: {
      type: Number,
      requires: true,
    },
  },
  data() {
    return {
      allChannels: [],
      isEdit: false, //控制编辑状态的显示
      fiexChannels: [0],
    };
  },
  created() {
    this.loadAllChannels();
  },
  computed: {
    ...mapState(["user"]),
    //计算属性会观测内部依赖数据的变化
    // 以来数据发生改变 则计算属性会重新执行
    recommendChannels() {
      return this.allChannels.filter((channel) => {
        //数组的find方法 遍历数组 把符合条件的第一个元素返回
        return !this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id;
        });
      });
    },

    // recommendChannels(){
    //     const channels=[]
    //   const ret =  this.allChannels.forEach(channel=>{
    //         this.myChannels.find(myChannel=>{
    //             return myChannel.id === channel.id
    //         })
    //         if(!ret){
    //             channels.push(channel)
    //         }
    //     })
    //     return channels
    // }
  },
  methods: {
    async loadAllChannels() {
      try {
        const { data } = await getAllChannels();
        this.allChannels = data.data.channels;
        // console.log(this.allChannels);
      } catch (err) {
        this.$toast("获取数据失败");
      }
    },
    async onAddChannel(channel) {
      this.myChannels.push(channel);

      // 数据持久化处理
      if (this.user) {
        try {
          // 已登录 把数据请求接口放到线上
          await addUserChannels({
            id: channel.id,
            seq: this.myChannels.length,
          });
        } catch (err) {
          this.$toast("保存失败，请稍后重试");
        }
      } else {
        // 未登录 把数据储存到本地
        setItem("TOUTIAO_CHANNELS", this.myChannels);
      }
    },
    onMyChannelClick(channel, index) {
      if (this.isEdit) {
        // 1. 如果是固定频道，则不删除
        if (this.fiexChannels.includes(channel.id)) {
          return;
        }

        // 2. 删除频道项
        this.myChannels.splice(index, 1);

        // 3. 如果删除的激活频道之前的频道，则更新激活的频道项
        // 参数1：要删除的元素的开始索引（包括）
        // 参数2：删除的个数，如果不指定，则从参数1开始一直删除到最后
        if (index <= this.active) {
          // 让激活频道的索引 - 1
          this.$emit("update-active", this.active - 1, true);
        }

        // 4. 处理持久化 (添加这行代码)
        this.deleteChannel(channel);
      } else {
        // 非编辑状态，执行切换频道
        this.$emit("update-active", index, false);
      }
    },
    async deleteChannel(channel) {
      try {
        if (this.user) {
          // 已登录，将数据存储到线上
          await deleteUserChannel(channel.id);
        } else {
          // 未登录，将数据存储到本地
          setItem("TOUTIAO_CHANNELS", this.myChannels);
        }
      } catch (err) {
        console.log(err);
        this.$toast("删除频道失败，请稍后重试");
      }
    },
  },
};
</script>

<style lang='less' scoped>
.channel-edit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    color: #333;
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 15px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
  /deep/.grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }
  /deep/.recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>